package common.store.web.controller;

import common.store.admin.dto.Category;
import common.store.admin.service.CategoryService;
import common.store.admin.service.impl.CategoryServiceImpl;
import common.store.common.util.C3p0Pool;
import common.store.common.util.MD5;
import common.store.web.bean.User;

import common.store.web.service.ProductService;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String username = req.getParameter("username");
        String password = MD5.stringMD5(req.getParameter("password"));

        String cart =req.getParameter("cart");
        String pid =req.getParameter("pid");

        QueryRunner qr = new QueryRunner(C3p0Pool.getDataSource());

        try {
            User user = qr.query("select u.uid , u.name  from user u where username = ? and password = ?"
                    , new BeanHandler<>(User.class) , username , password);
            if(user != null){
                HttpSession session = req.getSession();
                session.setAttribute("user" , user);
                if(!cart.equals("true"))
                {
                 req.getRequestDispatcher("home").forward(req,resp);
                resp.sendRedirect(req.getContextPath() + "/index.jsp");
                }
                else  {
                    req.getRequestDispatcher("/productInfo?pid="+pid).forward(req, resp);
                }
            }else{
                req.setAttribute("msg" , "用户名或密码错误！");
                req.getRequestDispatcher("/login.jsp").forward(req , resp);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req , resp);
    }
}
